package com.pai4j.message.interceptor;

import com.pai4j.message.core.interceptor.MessageInterceptor;
import com.pai4j.message.model.MessageContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

/**
 * 审计日志拦截器
 * 记录所有消息发送的审计日志
 *
 * @author PAI4J Team
 * @date 2025-11-01
 */
@Slf4j
@Component
@ConditionalOnProperty(prefix = "pai4j.message.interceptors.audit", name = "enabled", havingValue = "true", matchIfMissing = true)
public class AuditLogInterceptor implements MessageInterceptor {

    @Override
    public String getName() {
        return "audit-log";
    }

    @Override
    public boolean intercept(MessageContext context) {
        // 审计日志不拦截，只记录
        return true;
    }

    @Override
    public void preHandle(MessageContext context) {
        try {
            // 记录消息发送前的审计日志
            log.info("[消息审计] 准备发送消息: sender={}, receiver={}, category={}, type={}, resourceType={}, resourceId={}", 
                    context.getSenderId(),
                    context.getReceiverId(),
                    context.getCategory(),
                    context.getType(),
                    context.getResourceType(),
                    context.getResourceId());
        } catch (Exception e) {
            log.error("审计日志记录异常", e);
        }
    }

    @Override
    public void postHandle(MessageContext context, boolean result) {
        try {
            // 记录消息发送后的审计日志
            if (result) {
                log.info("[消息审计] 拦截器通过: sender={}, receiver={}", 
                        context.getSenderId(), context.getReceiverId());
            } else {
                log.warn("[消息审计] 拦截器拦截: sender={}, receiver={}, interceptor={}", 
                        context.getSenderId(), context.getReceiverId(), getName());
            }
        } catch (Exception e) {
            log.error("审计日志记录异常", e);
        }
    }

    @Override
    public int getOrder() {
        return 999; // 最低优先级，最后执行
    }

    @Override
    public String getDescription() {
        return "审计日志拦截器 - 记录所有消息发送的审计日志";
    }
}

